﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Billing.Dtos;
using Billing.Utilities;
using System.Configuration;
using System.Drawing.Printing;

namespace Billing.Windows
{
    /// <summary>
    /// Interaction logic for BookCake.xaml
    /// </summary>
    public partial class BookCake : Window
    {
        CakeBookingDto m_BokkingTODBDto = new CakeBookingDto();
        double discountValue = 0;
        double discountPercentage = 0;
        double extraValue = 0;
        double extraPercentage = 0;
        Color color = Colors.DarkOrange;
        Color warningColor = Colors.BurlyWood;
        Color noColor = Colors.Gray;
        //bool showMsg = false;
        DateTime selectedDeliveryDate;
        string discountReason = string.Empty;

        //0 - no extra
        //1 - extra in Rs
        //2 - extra in %
        //int extraType = 0;
        Color cursorEnterColor = Colors.Violet;
        Color cursorLeaveColor = Color.FromArgb(Convert.ToByte("FF", 16), Convert.ToByte("65", 16), Convert.ToByte("65", 16), Convert.ToByte("65", 16));

        public BookCake()
        {
            try
            {
                InitializeComponent();
                txtCustomerName.Focus();
                SetDefaultValues();
                billNo.Text = Database.BranchLetter + Database.GetNextCakeBillNo().ToString();

                for (int cnt = 0; cnt < 20; cnt++)
                {
                    dtDeliveryDt.Items.Add(new ListBoxItem { Tag = DateTime.Now.AddDays(cnt), Content = DateTime.Now.AddDays(cnt).DayOfWeek.ToString() + " " + DateTime.Now.AddDays(cnt).ToString("dd-MMM-yyyy") });
                }
                dtDeliveryDt.SelectedIndex = 0;
                lstTime.SelectedIndex = 0;
                lstPhoto.SelectedIndex = 0;
                lbShape.SelectedIndex = 0;
            }
            catch (Exception)
            { }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Escape)
                {
                    this.Close();
                }
                else if (e.Key == Key.F1)
                {
                    if (ValidateFields())
                    {
                        if (MessageBoxResult.OK == MessageBox.Show("Do you want to order the cake?", "Confirm Order", MessageBoxButton.OKCancel, MessageBoxImage.Information))
                        {
                            //TODO
                            //int result = 0;

                            int result = Database.AddNewCake(billNo.Text, txtCustomerName.Text, txtCustomerPhone.Text, selectedDeliveryDate.ToString("MM/dd/yyyy"), (lstTime.SelectedItem as ListBoxItem).Content.ToString(), (lbShape.SelectedItem != null ? (lbShape.SelectedItem as ListBoxItem).Tag.ToString() : "0"), txtModel.Text, description.Text, txtMessage.Text, ((CakeFlavour)(lbFlavour.SelectedItem)).FlavourID, double.Parse(tbQty.Text == string.Empty ? "0" : tbQty.Text), double.Parse(txtTotalAmtNotExtra.Text == string.Empty ? "0" : txtTotalAmtNotExtra.Text), double.Parse((txtExtraPercentage.Text == string.Empty || txtExtraPercentage.Text == "Press F4 / F5") ? "0" : txtExtraPercentage.Text), extraValue, double.Parse(txtAdvance.Text == string.Empty ? "0" : txtAdvance.Text), double.Parse(txtBalance.Text == string.Empty ? "0" : txtBalance.Text), double.Parse(txtNetAmount.Text == string.Empty ? "0" : txtNetAmount.Text), discountPercentage, discountValue, true, discountReason.Replace("'", string.Empty), (lstPhoto.SelectedItem as ListBoxItem).Content.ToString(), tbBillNo.Text);
                            if (result > 0)
                            {
                                MessageBox.Show("Cake Ordered Successfully. Order # : " + billNo.Text, "Cake Ordered", MessageBoxButton.OK, MessageBoxImage.Information);

                                bool isChefCopyRequired = false;

                                if (selectedDeliveryDate.Day == DateTime.Now.Day && selectedDeliveryDate.Month == DateTime.Now.Month)
                                {
                                    if (MessageBoxResult.OK == MessageBox.Show("Do you require Chef Copy?", "Chef Copy", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                                        isChefCopyRequired = true;
                                }

                                //TODO
                                if (ConfigurationManager.AppSettings["PrinterType"] != null && ConfigurationManager.AppSettings["PrinterType"].ToString() == "new")
                                {
                                    NewCakePrinter form = new NewCakePrinter(billNo.Text, DateTime.Now.ToString("dd-MMM-yy  hh:mm:tt"), selectedDeliveryDate.ToString("dd/MM/yyyy") + "  " + (lstTime.SelectedItem as ListBoxItem).Content.ToString(), txtCustomerName.Text, txtCustomerPhone.Text, (lbShape.SelectedItem != null ? (lbShape.SelectedItem as ListBoxItem).Content.ToString() : string.Empty), txtModel.Text, description.Text, txtMessage.Text, ((CakeFlavour)(lbFlavour.SelectedItem)).Flavour, tbQty.Text, extraValue.ToString(), (txtNetAmount.Text == string.Empty ? "0" : txtNetAmount.Text).ToString(), (txtAdvance.Text == string.Empty ? "0" : txtAdvance.Text).ToString(), (txtBalance.Text == string.Empty ? "0" : txtBalance.Text).ToString(), discountValue.ToString(), false, (lstPhoto.SelectedItem as ListBoxItem).Content.ToString(), tbBillNo.Text);
                                    form.printDocument1.PrintController = new StandardPrintController();
                                    form.printDocument1.Print();
                                    form.Dispose();

                                    if (isChefCopyRequired)
                                    {
                                        Database.SetCakeChefCopyPrinted(billNo.Text);
                                        NewCakePrinter form1 = new NewCakePrinter(billNo.Text, DateTime.Now.ToString("dd-MMM-yy  hh:mm:tt"), selectedDeliveryDate.ToString("dd/MM/yyyy") + "  " + (lstTime.SelectedItem as ListBoxItem).Content.ToString(), txtCustomerName.Text, txtCustomerPhone.Text, (lbShape.SelectedItem != null ? (lbShape.SelectedItem as ListBoxItem).Content.ToString() : string.Empty), txtModel.Text, description.Text, txtMessage.Text, ((CakeFlavour)(lbFlavour.SelectedItem)).Flavour, tbQty.Text, extraValue.ToString(), (txtNetAmount.Text == string.Empty ? "0" : txtNetAmount.Text).ToString(), (txtAdvance.Text == string.Empty ? "0" : txtAdvance.Text).ToString(), (txtBalance.Text == string.Empty ? "0" : txtBalance.Text).ToString(), discountValue.ToString(), true, (lstPhoto.SelectedItem as ListBoxItem).Content.ToString(), tbBillNo.Text);
                                        form1.printDocument1.PrintController = new StandardPrintController();
                                        form1.printDocument1.Print();
                                        form1.Dispose();
                                    }
                                }
                                else
                                {
                                    OldCakePrinter form = new OldCakePrinter(billNo.Text, DateTime.Now.ToString("dd-MMM-yy  hh:mm:tt"), selectedDeliveryDate.ToString("dd/MM/yyyy") + "  " + (lstTime.SelectedItem as ListBoxItem).Content.ToString(), txtCustomerName.Text, txtCustomerPhone.Text, (lbShape.SelectedItem != null ? (lbShape.SelectedItem as ListBoxItem).Content.ToString() : string.Empty), txtModel.Text, description.Text, txtMessage.Text, ((CakeFlavour)(lbFlavour.SelectedItem)).Flavour, tbQty.Text, extraValue.ToString(), (txtNetAmount.Text == string.Empty ? "0" : txtNetAmount.Text).ToString(), (txtAdvance.Text == string.Empty ? "0" : txtAdvance.Text).ToString(), (txtBalance.Text == string.Empty ? "0" : txtBalance.Text).ToString(), discountValue.ToString(), false, (lstPhoto.SelectedItem as ListBoxItem).Content.ToString(), tbBillNo.Text);
                                    form.printDocument1.PrintController = new StandardPrintController();
                                    form.printDocument1.Print();
                                    form.Dispose();

                                    if (isChefCopyRequired)
                                    {
                                        Database.SetCakeChefCopyPrinted(billNo.Text);
                                        OldCakePrinter form1 = new OldCakePrinter(billNo.Text, DateTime.Now.ToString("dd-MMM-yy  hh:mm:tt"), selectedDeliveryDate.ToString("dd/MM/yyyy") + "  " + (lstTime.SelectedItem as ListBoxItem).Content.ToString(), txtCustomerName.Text, txtCustomerPhone.Text, (lbShape.SelectedItem != null ? (lbShape.SelectedItem as ListBoxItem).Content.ToString() : string.Empty), txtModel.Text, description.Text, txtMessage.Text, ((CakeFlavour)(lbFlavour.SelectedItem)).Flavour, tbQty.Text, extraValue.ToString(), (txtNetAmount.Text == string.Empty ? "0" : txtNetAmount.Text).ToString(), (txtAdvance.Text == string.Empty ? "0" : txtAdvance.Text).ToString(), (txtBalance.Text == string.Empty ? "0" : txtBalance.Text).ToString(), discountValue.ToString(), true, (lstPhoto.SelectedItem as ListBoxItem).Content.ToString(), tbBillNo.Text);
                                        form1.printDocument1.PrintController = new StandardPrintController();
                                        form1.printDocument1.Print();
                                        form1.Dispose();
                                    }
                                }
                                this.Close();
                            }
                            else
                            {
                                MessageBox.Show("Some Error Has Occurred. Please try again later.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                        }
                    }
                }
                else if (e.Key == Key.F2 && txtNetAmount.Text != string.Empty)
                {
                    //DiscountForCake discount = new DiscountForCake(this, false);
                    DiscountForCake discount = new DiscountForCake(false);
                    discount.m_discountInRs = false;
                    discount.m_TotalAmount = double.Parse(txtTotalAmtNotExtra.Text);
                    discount.Owner = this;
                    discount.ShowDialog();
                    discountValue = discount.m_DiscountAmount;
                    discountPercentage = discount.m_DiscountPercentage;
                    txtDiscount.Text = discountValue.ToString();
                    discountReason = discount.txtDiscountReason.Text;
                    ChangeValues();
                    //lblNetTotal.Content = BookingToDBDto.NetTotal.ToString();
                }
                else if (e.Key == Key.F3 && txtNetAmount.Text != string.Empty)
                {
                    //DiscountForCake discount = new DiscountForCake(this, true);
                    DiscountForCake discount = new DiscountForCake(true);
                    discount.m_discountInRs = true;
                    discount.m_TotalAmount = double.Parse(txtTotalAmtNotExtra.Text);
                    discount.Owner = this;
                    discount.ShowDialog();
                    discountValue = discount.m_DiscountAmount;
                    discountPercentage = discount.m_DiscountPercentage;
                    txtDiscount.Text = discountValue.ToString();
                    discountReason = discount.txtDiscountReason.Text;
                    ChangeValues();
                    //lblNetTotal.Content = BookingToDBDto.NetTotal.ToString();
                }
                else if (e.Key == Key.F4 && txtNetAmount.Text != string.Empty)
                {
                    ExtraForCake extra = new ExtraForCake(false);
                    //extra.m_discountInRs = false;
                    extra.m_TotalAmount = double.Parse(txtTotalAmtNotExtra.Text);
                    extra.Owner = this;
                    extra.ShowDialog();
                    //discountValue = extra.m_DiscountAmount;
                    //discountPercentage = extra.m_DiscountPercentage;
                    //txtExtraPercentage.Text = discountValue.ToString();
                    //discountReason = extra.txtDiscountReason.Text;
                    //extraType = 2;
                    txtExtraPercentage.Text = extra.m_ExtraAmount.ToString();
                    ChangeValues();
                    //lblNetTotal.Content = BookingToDBDto.NetTotal.ToString();
                }
                else if (e.Key == Key.F5 && txtNetAmount.Text != string.Empty)
                {
                    ExtraForCake extra = new ExtraForCake(true);
                    //extra.m_discountInRs = false;
                    extra.m_TotalAmount = double.Parse(txtTotalAmtNotExtra.Text);
                    extra.Owner = this;
                    extra.ShowDialog();
                    //discountValue = extra.m_DiscountAmount;
                    //discountPercentage = extra.m_DiscountPercentage;
                    //txtExtraPercentage.Text = discountValue.ToString();
                    //discountReason = extra.txtDiscountReason.Text;
                    //extraType = 1;
                    txtExtraPercentage.Text = extra.m_ExtraAmount.ToString();
                    ChangeValues();
                    //lblNetTotal.Content = BookingToDBDto.NetTotal.ToString();
                }
                //else if (e.Key == Key.F4)
                //{
                //    PayType payType = new PayType(this);
                //    payType.Owner = this;
                //    payType.ShowDialog();
                //}
            }
            catch (Exception) { }
        }

        private bool ValidateFields()
        {
            try
            {
                bool isValid = true;
                UIElement element = null;

                /*if (txtCustomerName.Text == string.Empty)
                {
                    brdrCustomer.Background = new SolidColorBrush(color);
                    element = txtCustomerName;
                    isValid = false;
                }
                else
                {
                    brdrCustomer.Background = new SolidColorBrush(noColor);
                }*/
                if (txtCustomerName.Text == string.Empty)
                {
                    txtCustomerName.Text = " ";
                }

                /*if (txtCustomerPhone.Text.Trim() == string.Empty)
                {
                    brdrPhone.Background = new SolidColorBrush(color);
                    if (element == null)
                        element = txtCustomerPhone;
                    isValid = false;
                }
                else
                {
                    brdrPhone.Background = new SolidColorBrush(noColor);
                }*/
                if (txtCustomerPhone.Text == string.Empty)
                {
                    txtCustomerName.Text = " ";
                }

                if (lbShape.SelectedIndex == -1 && txtModel.Text.Trim() == string.Empty)
                {
                    //MessageBox.Show("Select Valid Shape", "Invalid Shape", MessageBoxButton.OK, MessageBoxImage.Error);
                    brdrShape.Background = new SolidColorBrush(color);
                    if (element == null && lbShape.SelectedIndex == -1)
                    {
                        element = lbShape;
                    }

                    brdrAlbum.Background = new SolidColorBrush(color);
                    if (element == null)
                    {
                        element = txtModel;
                    }
                    isValid = false;
                }
                else
                {
                    brdrShape.Background = new SolidColorBrush(noColor);
                    brdrAlbum.Background = new SolidColorBrush(noColor);
                }

                /*if (cbAlbumModel.SelectedIndex == -1)
                {
                    //MessageBox.Show("Select Valid Album Model", "Invalid Album Model", MessageBoxButton.OK, MessageBoxImage.Error);
                    brdrAlbum.Background = new SolidColorBrush(color);
                    if (element == null)
                        element = cbAlbumModel;
                    isValid = false;
                }
                else
                {
                    brdrAlbum.Background = new SolidColorBrush(noColor);
                }*/

                if (txtMessage.Text.Trim() == string.Empty)
                {
                    //MessageBox.Show("Enter valid Message", "Invalid Message", MessageBoxButton.OK, MessageBoxImage.Error);
                    brdrMessage.Background = new SolidColorBrush(color);
                    if (element == null)
                    {
                        element = txtMessage;
                    }
                    isValid = false;
                }
                else
                {
                    brdrMessage.Background = new SolidColorBrush(noColor);
                }

                if (lbFlavour.SelectedIndex == -1)
                {
                    //MessageBox.Show("Enter valid Flavour", "Invalid Flavour", MessageBoxButton.OK, MessageBoxImage.Error);
                    brdrFlavour.Background = new SolidColorBrush(color);
                    if (element == null)
                    {
                        element = lbFlavour;
                    }
                    isValid = false;
                }
                else
                {
                    brdrFlavour.Background = new SolidColorBrush(noColor);
                }

                if (tbQty.Text.Trim() == string.Empty)
                {
                    //MessageBox.Show("Enter valid Quantity", "Invalid Quantity", MessageBoxButton.OK, MessageBoxImage.Error);
                    brdrQty.Background = new SolidColorBrush(color);
                    if (element == null)
                    {
                        element = tbQty;
                    }
                    isValid = false;
                }
                else
                {
                    brdrQty.Background = new SolidColorBrush(noColor);
                }

                /*if (description.Text.Trim() == string.Empty)
                {
                    //MessageBox.Show("Enter valid Description", "Invalid Description", MessageBoxButton.OK, MessageBoxImage.Error);
                    brdrDesc.Background = new SolidColorBrush(color);
                    if (element == null)
                        element = description;
                    isValid = false;
                }
                else
                {
                    brdrDesc.Background = new SolidColorBrush(noColor);
                }*/
                if (description.Text == string.Empty)
                {
                    description.Text = " ";
                }

                DateTime dtselect = DateTime.Parse((dtDeliveryDt.SelectedItem as ListBoxItem).Tag.ToString());
                selectedDeliveryDate = new DateTime(dtselect.Year, dtselect.Month, dtselect.Day);
                //TODO
                selectedDeliveryDate = selectedDeliveryDate.AddHours(double.Parse(((lstTime.SelectedItem as ListBoxItem).Tag.ToString())));
                //selectedDeliveryDate = selectedDeliveryDate.AddHours(0);
                //if (txtTimeConst.SelectionBoxItem.ToString() == "AM")
                //    selectedDeliveryDate.AddHours(txtTime.Value);
                //else
                //    selectedDeliveryDate = selectedDeliveryDate.AddHours(txtTime.Value + 12);

                TimeSpan ts = selectedDeliveryDate - DateTime.Now;

                if (ts.Days <= 0 && selectedDeliveryDate.Day == DateTime.Now.Day)
                {
                    if (ts.Hours <= 0)
                    {
                        brdrDate.Background = new SolidColorBrush(color);
                        brdrTime.Background = new SolidColorBrush(color);
                        //showMsg = false;
                        if (element == null)
                        {
                            element = dtDeliveryDt;
                        }
                        isValid = false;
                    }
                    else
                    {
                        //showMsg = true;
                        brdrDate.Background = new SolidColorBrush(warningColor);
                        brdrTime.Background = new SolidColorBrush(warningColor);
                    }
                }
                else
                {
                    //showMsg = false;
                    brdrDate.Background = new SolidColorBrush(noColor);
                    brdrTime.Background = new SolidColorBrush(noColor);
                    //brdrAMorPM.Background = new SolidColorBrush(noColor);
                }

                int temp = 0;
                if (tbBillNo.Text.Trim() == string.Empty || !(int.TryParse(tbBillNo.Text, out temp)))
                {
                    brdrBillNo.Background = new SolidColorBrush(warningColor);
                    isValid = false;
                }
                else
                {
                    brdrBillNo.Background = new SolidColorBrush(noColor);
                }

                if (element != null)
                {
                    element.Focus();
                }

                if (!(isValid))
                {
                    MessageBox.Show("Some fields are invalid. Please fill correctly.", "Fill Mandatory Fields", MessageBoxButton.OK, MessageBoxImage.Error);
                }

                //Check whether the Bill Number with Same Delivery Date exists
                if (isValid)
                {
                    bool res = Database.IsExistsBillNoAndBookingDate(tbBillNo.Text, DateTime.Now);
                    if (res)
                    {
                        isValid = false;
                        MessageBox.Show("Please enter valid Bill Number", "Invalid Bill No", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                //if (isValid)// && showMsg)
                //{
                //    if (MessageBoxResult.Cancel == MessageBox.Show("You are booking the cake to deliver today in very short period (in just " + ts.Hours.ToString() + " Hrs). Do you want to continue?", "Short Period Cake Book", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                //    {
                //        dtDeliveryDt.Focus();
                //        return false;
                //    }
                //}

                return isValid;
            }
            catch (Exception) { }
            return false;
        }

        void SetDefaultValues()
        {
            try
            {
                //lbShape.ItemsSource = Database.GetCakeShapes();
                foreach (CakeShape cs in Database.GetCakeShapes())
                {
                    lbShape.Items.Add(new ListBoxItem { Content = cs.Shape, Tag = cs.ID });
                }

                //lbShape.DisplayMemberPath = "Shape";

                lbFlavour.ItemsSource = Database.GetCakeFlavours();
                lbFlavour.DisplayMemberPath = "Flavour";
                lbFlavour.SelectedIndex = 0;
            }
            catch (Exception) { }
        }

        private void txtCustomerName_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right)
                {
                    if (txtCustomerName.Text == string.Empty)
                        txtCustomerName.Text = " ";
                    txtCustomerPhone.Focus();
                    txtCustomerPhone.SelectAll();
                }
            }
            catch (Exception) { }
        }

        private void txtExtraPercentage_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right)
                {
                    if (txtExtraPercentage.Text.Trim() == string.Empty)
                        txtExtraPercentage.Text = "0";
                    txtAdvance.Focus();
                    txtAdvance.SelectAll();
                }
                else if (e.Key == Key.Left)
                {
                    description.Focus();
                }
            }
            catch (Exception) { }
        }

        private void lbShape_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right && lbShape.SelectedItems.Count == 1)
                {
                    int index = lbShape.SelectedIndex;
                    txtModel.Focus();
                    lbShape.SelectedIndex = index;
                }
                else if (e.Key == Key.Left)
                {
                    int index = lbShape.SelectedIndex;
                    txtCustomerPhone.Focus();
                    txtCustomerPhone.SelectAll();
                    lbShape.SelectedIndex = index;
                }
            }
            catch (Exception) { }
        }

        private void txtCustomerPhone_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right)
                {
                    if (txtCustomerPhone.Text == string.Empty)
                        txtCustomerPhone.Text = " ";
                    lbShape.Focus();

                    if (lbShape.SelectedIndex == -1)
                        lbShape.SelectedIndex = 0;
                }
                else if (e.Key == Key.Left)
                {
                    txtCustomerName.Focus();
                    txtCustomerName.SelectAll();
                }
            }
            catch (Exception) { }
        }

        private void txtMessage_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right)
                {
                    if (txtMessage.Text == string.Empty)
                        txtMessage.Text = " ";
                    dtDeliveryDt.Focus();
                }
                else if (e.Key == Key.Left)
                {
                    txtModel.Focus();
                    txtModel.SelectAll();
                }
            }
            catch (Exception) { }
        }

        private void lbFlavour_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right)
                {
                    tbQty.Focus();
                    tbQty.SelectAll();
                }
                else if (e.Key == Key.Left)
                {
                    //TODO
                    //cmbTime.Focus();
                    lstTime.Focus();
                }
            }
            catch (Exception) { }
        }

        private void tbQty_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right)
                {
                    if (tbQty.Text.Trim() == string.Empty)
                        tbQty.Text = "1";
                    description.Focus();
                    description.SelectAll();
                }
                else if (e.Key == Key.Left)
                {
                    lbFlavour.Focus();
                }
            }
            catch (Exception) { }
        }

        public CakeBookingDto BookingToDBDto
        {
            get
            {
                return m_BokkingTODBDto;
            }
            set
            {
                m_BokkingTODBDto = value;
            }
        }

        private void tbQty_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (tbQty.Text != string.Empty && tbQty.Text != ".")
                {
                    double value;
                    if (double.TryParse(tbQty.Text, out value))
                    {
                        tbAmount.Text = (double.Parse(tbPricePerKG.Text) * value).ToString();
                        txtTotalAmtNotExtra.Text = (double.Parse(tbAmount.Text) + double.Parse((lstPhoto.SelectedItem as ListBoxItem).Tag.ToString())).ToString();
                        ChangeValues();
                    }
                    else
                    {
                        tbQty.Clear();
                    }
                }
                else
                {
                    tbAmount.Clear();
                    tbTotalAmount.Clear();
                }
            }
            catch (Exception) { }
        }

        private void lbFlavour_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                CakeFlavour selectedFlavour = (sender as ListBox).SelectedItem as CakeFlavour;
                tbPricePerKG.Text = selectedFlavour.PricePerKG.ToString();

                if (tbQty.Text != string.Empty)
                {
                    double value;
                    if (double.TryParse(tbQty.Text, out value))
                    {
                        txtTotalAmtNotExtra.Text = tbTotalAmount.Text = (double.Parse(tbPricePerKG.Text) * value).ToString();
                    }
                    else
                    {
                        tbQty.Clear();
                    }
                    ChangeValues();
                }
            }
            catch (Exception) { }
        }

        private void txtExtraPercentage_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                double value;
                if (!(double.TryParse(txtExtraPercentage.Text, out value)))
                {
                    txtExtraPercentage.Text = string.Empty;
                }
                ChangeValues();
            }
            catch (Exception) { }
        }

        private void ChangeValues()
        {
            try
            {
                double total = txtTotalAmtNotExtra.Text == string.Empty ? 0 : double.Parse(txtTotalAmtNotExtra.Text);
                extraPercentage = (txtExtraPercentage.Text == string.Empty || txtExtraPercentage.Text == "Press F4 / F5") ? 0 : double.Parse(txtExtraPercentage.Text);
                double advance = txtAdvance.Text == string.Empty ? 0 : double.Parse(txtAdvance.Text);
                double discount = (txtDiscount.Text == string.Empty || txtDiscount.Text == "Press F2 / F3") ? 0 : double.Parse(txtDiscount.Text);

                extraValue = extraPercentage;
                txtNetAmount.Text = (total + extraPercentage - discount).ToString();
                txtBalance.Text = (total + extraPercentage - advance - discount).ToString();
            }
            catch (Exception) { }
        }

        private void txtAdvance_TextChanged(object sender, TextChangedEventArgs e)
        {
            ChangeValues();
        }

        private void description_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right)
                {
                    if (description.Text == string.Empty)
                        description.Text = " ";
                    txtExtraPercentage.Focus();
                    txtExtraPercentage.SelectAll();
                }
                else if (e.Key == Key.Left)
                {
                    tbQty.Focus();
                }
            }
            catch (Exception) { }
        }

        private void lbShape_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbShape.SelectedIndex != -1)
                {
                    txtModel.Clear();
                }
            }
            catch (Exception) { }
        }

        private void txtModel_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (txtModel.Text != string.Empty)
                {
                    lbShape.SelectedIndex = -1;
                }
            }
            catch (Exception) { }
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right)
                {
                    if (txtAdvance.IsFocused)
                        return;

                    TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
                    UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
                    if (elementWithFocus != null)
                        elementWithFocus.MoveFocus(request);

                    if (txtTotalAmtNotExtra.IsFocused)
                    {
                        elementWithFocus = Keyboard.FocusedElement as UIElement;
                        if (elementWithFocus != null)
                            elementWithFocus.MoveFocus(request);
                    }

                    if (txtExtraPercentage.IsFocused)
                    {
                        elementWithFocus = Keyboard.FocusedElement as UIElement;
                        if (elementWithFocus != null)
                            elementWithFocus.MoveFocus(request);
                    }
                }
                else if (e.Key == Key.Left)
                {
                    if (txtCustomerName.IsFocused)
                        return;

                    TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Previous);
                    UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
                    if (elementWithFocus != null)
                        elementWithFocus.MoveFocus(request);

                    if (txtExtraPercentage.IsFocused)
                    {
                        elementWithFocus = Keyboard.FocusedElement as UIElement;
                        if (elementWithFocus != null)
                            elementWithFocus.MoveFocus(request);
                    }

                    if (txtTotalAmtNotExtra.IsFocused)
                    {
                        elementWithFocus = Keyboard.FocusedElement as UIElement;
                        if (elementWithFocus != null)
                            elementWithFocus.MoveFocus(request);
                    }
                }
            }
            catch (Exception) { }
        }

        private bool IsListBoxFocused(UIElement lstBox)
        {
            try
            {
                foreach (ListBoxItem item in (lstBox as ListBox).Items)
                {
                    if (item.IsFocused)
                        return true;
                }
            }
            catch (Exception) { }
            return false;
        }

        private void txt_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                ((sender as TextBox).Parent as Border).Background = new SolidColorBrush(cursorEnterColor);
            }
            catch (Exception) { }
        }

        private void txt_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                ((sender as TextBox).Parent as Border).Background = new SolidColorBrush(cursorLeaveColor);
            }
            catch (Exception) { }
        }

        private void lst_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                ((sender as ListBox).Parent as Border).Background = new SolidColorBrush(cursorEnterColor);
            }
            catch (Exception) { }
        }

        private void lst_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                ((sender as ListBox).Parent as Border).Background = new SolidColorBrush(cursorLeaveColor);
            }
            catch (Exception) { }
        }

        private void dt_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                (((sender as ListBox).Parent as StackPanel).Parent as Border).Background = new SolidColorBrush(cursorEnterColor);
            }
            catch (Exception) { }
        }

        private void dt_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                (((sender as ListBox).Parent as StackPanel).Parent as Border).Background = new SolidColorBrush(cursorLeaveColor);
            }
            catch (Exception) { }
        }

        private void cmb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                ((sender as ComboBox).Parent as Border).Background = new SolidColorBrush(cursorEnterColor);
            }
            catch (Exception) { }
        }

        private void cmb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            try
            {
                ((sender as ComboBox).Parent as Border).Background = new SolidColorBrush(cursorLeaveColor);
            }
            catch (Exception) { }
        }

        private void dtDeliveryDt_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Right)
            {
                e.Handled = false;
            }
        }

        private void lstPhoto_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (tbQty.Text != string.Empty && tbQty.Text != ".")
                {
                    double value;
                    if (double.TryParse(tbQty.Text, out value))
                    {
                        tbAmount.Text = (double.Parse(tbPricePerKG.Text) * value).ToString();
                        txtTotalAmtNotExtra.Text = (double.Parse(tbAmount.Text) + double.Parse((lstPhoto.SelectedItem as ListBoxItem).Tag.ToString())).ToString();
                        ChangeValues();
                    }
                    else
                    {
                        tbQty.Clear();
                    }
                }
                else
                {
                    tbAmount.Clear();
                    tbTotalAmount.Clear();
                }
            }
            catch (Exception) { }
        }
    }
}

